/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2022-12-05     yoyoyes      first version
 */

#include "thread_event_demo.h"

static struct rt_event event;

ALIGN(RT_ALIGN_SIZE)
static char thread1_stack[1024];
static struct rt_thread thread1;

/*
 * @brief  线程1入口函数
 *
 * @param  parameter 线程1入口函数参数
 *
 * @return None
 */
static void thread1_recv_event(void *parameter)
{
    rt_uint32_t e;

    /* 第一次接收事件，事件3或事件5任意一个可以触发线程1，接收完成后清除事件标志 */
    if(rt_event_recv(&event, (EVENT_FLAG3 | EVENT_FLAG5), RT_EVENT_FLAG_OR | RT_EVENT_FLAG_CLEAR, RT_WAITING_FOREVER, &e) == RT_EOK)
    {
        rt_kprintf("thread1: OR recv event 0x%x\n", e);
    }

    rt_kprintf("thread1: delay 1s to prepare the second event\n");
    rt_thread_mdelay(1000);

    /* 第二次接收事件，事件3和事件5均发生才可以触发线程1，接收完成后清除事件标志 */
    if(rt_event_recv(&event, (EVENT_FLAG3 | EVENT_FLAG5), RT_EVENT_FLAG_AND | RT_EVENT_FLAG_CLEAR, RT_WAITING_FOREVER, &e) == RT_EOK)
    {
        rt_kprintf("thread1: AND recv event 0x%x\n");
    }

    /* 只有接收事件3和事件5才打印以下信息 */
    rt_kprintf("thread1 leave.\n");
}

ALIGN(RT_ALIGN_SIZE)
static char thread2_stack[1024];
static struct rt_thread thread2;

/*
 * @brief  线程2入口函数
 *
 * @param  parameter 线程2入口函数参数
 *
 * @return None
 */
static void thread2_send_event(void *parameter)
{
    rt_kprintf("thread2: send event3\n");
    rt_event_send(&event, EVENT_FLAG3);
    rt_thread_mdelay(200);

    rt_kprintf("thread2: send event5\n");
    rt_event_send(&event, EVENT_FLAG5);
    rt_thread_mdelay(200);

    rt_kprintf("thread2: send event3\n");
    rt_event_send(&event, EVENT_FLAG3);
    rt_kprintf("thread2 leave.\n");
}

/*
 * @brief  事件集Demo函数
 *
 * @param  None
 *
 * @return None
 */
int thread_event_demo(void)
{
    rt_err_t result;

    result = rt_event_init(&event, "event", RT_IPC_FLAG_PRIO);
    if(result != RT_NULL)
    {
        rt_kprintf("init event failed.\n");
        return -1;
    }

    rt_thread_init(&thread1, "thread1", thread1_recv_event, RT_NULL, &thread1_stack[0], sizeof(thread1_stack), THREAD_PRIORITY - 1, THREAD_TIMESLICE);
    rt_thread_startup(&thread1);

    rt_thread_init(&thread2, "thread2", thread2_send_event, RT_NULL, &thread2_stack[0], sizeof(thread2_stack), THREAD_PRIORITY, THREAD_TIMESLICE);
    rt_thread_startup(&thread2);

    return 0;
}
